package com.flightcloud.ssm;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.filter.logging.Slf4jLogFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.pagination.DialectFactory;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;

//@Configuration
public class DBConfig {

	@Value("${jdbc.username}")
	private String username;
	@Value("${jdbc.password}")
	private String password;
	@Value("${jdbc.url}")
	private String url;
	@Value("${jdbc.driver}")
	private String driver;

	@Bean
	public javax.sql.DataSource dateSource(Environment env) {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setUsername(env.getRequiredProperty("jdbc.username"));
		dataSource.setPassword(env.getRequiredProperty("jdbc.password"));
		dataSource.setUrl(env.getRequiredProperty("jdbc.url"));
		dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driver"));
		// dataSource.setUsername(username);
		// dataSource.setPassword(password);
		// dataSource.setDriverClassName(driver);
		// dataSource.setUrl(url);

		dataSource.setInitialSize(1);
		dataSource.setMinIdle(1);
		dataSource.setMaxActive(50);

		dataSource.setMaxWait(10000);

		dataSource.setTimeBetweenEvictionRunsMillis(60000);
		dataSource.setMinEvictableIdleTimeMillis(300000);

		dataSource.setTestWhileIdle(true);

		dataSource.setTestOnBorrow(true);
		dataSource.setTestOnReturn(false);

		dataSource.setPoolPreparedStatements(true);
		dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);

		dataSource.setValidationQuery("select 1");
		dataSource.setRemoveAbandonedTimeout(60);

		try {
			dataSource.setFilters("stat");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Slf4jLogFilter logFilter = new Slf4jLogFilter();
		logFilter.setStatementExecutableSqlLogEnable(false);
		List<Filter> filters = new ArrayList<>();
		filters.add(logFilter);
		dataSource.setProxyFilters(filters);
		return dataSource;
	}

	/**
	 * 
	 * 描述 创建sqlSessionFactoryBean
	 * 
	 * @param dataSource
	 * @return
	 * @throws IOException
	 *
	 */
//	@Bean(name = "sqlSessionFactoryBean")
//	public SqlSessionFactoryBean createSqlSessionFactoryBean(javax.sql.DataSource dataSource,
//			ResourcePatternResolver resourceLoader) throws IOException {
//		SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
//		sqlSessionFactory.setDataSource(dataSource);
//		Resource[] resources = resourceLoader.getResources("classpath:com/flightcloud/ssm/*/*/xml/*Mapper.xml");
//		sqlSessionFactory.setMapperLocations(resources);
//		sqlSessionFactory.setConfigLocation(resourceLoader.getResource("classpath:mybatis.xml"));
//		return sqlSessionFactory;
//	}

	@Bean
	public MapperScannerConfigurer mapperScannerConfigurer(ApplicationContext ac) {
		MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
		scannerConfigurer.setBasePackage("com.flightcloud.ssm.*.mapper");
		// scannerConfigurer.setSqlSessionFactory(sqlSessionFactory);
		scannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
		return scannerConfigurer;
	}
	
	@Bean(name = "sqlSessionFactoryBean")
	public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean(javax.sql.DataSource dataSource,
			ResourcePatternResolver resourceLoader,GlobalConfiguration globalConfiguration) throws IOException {
		MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
		sqlSessionFactory.setDataSource(dataSource);
		Resource[] resources = resourceLoader.getResources("classpath:com/flightcloud/ssm/*/*/xml/*Mapper.xml");
		sqlSessionFactory.setMapperLocations(resources);
		sqlSessionFactory.setConfigLocation(resourceLoader.getResource("classpath:mybatis.xml"));
		PaginationInterceptor interceptor = new PaginationInterceptor();
		interceptor.setDialectType("mysql");
		sqlSessionFactory.setPlugins(new PaginationInterceptor[]{interceptor});
		sqlSessionFactory.setGlobalConfig(globalConfiguration);
		return sqlSessionFactory;
	}

//	<array>
//    <!-- 分页插件配置 -->
//    <bean id="paginationInterceptor" class="com.baomidou.mybatisplus.plugins.PaginationInterceptor">
//        <property name="dialectType" value="mysql"/>
//    </bean>
//</array>
	
	@Bean
	public GlobalConfiguration globalConfiguration(){
		GlobalConfiguration configuration = new GlobalConfiguration();
		configuration.setIdType(IdType.AUTO.getKey());
		configuration.setDbType(DBType.MYSQL.getDb());
		configuration.setDbColumnUnderline(true);
		return configuration;
	}

	// @Bean
	// public DataSourceTransactionManager
	// dataSourceTransactionManager(javax.sql.DataSource dataSource) {
	// DataSourceTransactionManager transactionManager = new
	// DataSourceTransactionManager();
	// transactionManager.setDataSource(dataSource);
	// return transactionManager;
	// }
}
